# coding=utf-8
import os
from string import Template
from typing import  List
from parse.parse_types import  Module
from parse.sdb_parser import ECU

from utils.util import  removeDir, writeFile

SomeIP_proto = Template(
"""syntax = "proto2";
option optimize_for = LITE_RUNTIME;

package proto.ipcp;

${messageList}

""")

message_template=Template(
"""
message ${name} {
${content}
}
"""
)

Android_bp=Template(
"""
cc_library {
    name: "${name}",
    proprietary: true,
    proto: {
        export_proto_headers: true,
        type: "lite",
    },
    strip: {
        keep_symbols: true,
    },
    srcs: ["apvp.proto"]
}

java_library {
    name: "car.proto.apvp",
    proto: {
        type: "nano",
    },
    srcs: ["apvp.proto"],
    product_variables: {
        pdk: {
            enabled: false,
        },
    },
    platform_apis: true,
    sdk_version: "current",
    min_sdk_version: "33",
    apex_available: [
        "com.android.car.framework",
        "//apex_available:platform",
    ],
}

"""
)


def gen_APVPProtoBuf(modules:List[Module],ecus:List[ECU],directTransmitList:List[str],outDir:str,proto_name:str):
    #整理数据,以serviceId划分一组message,并只需要有透传的
    messageList=[]
    for module in modules:
        for cb in [item for item in module.cb_apis if item.api in directTransmitList]:
            if cb.getPayload().isStructPayload():
                structPayload=cb.getPayload().getStructPayload()
                messageList.append(message_template.substitute(
                    name = structPayload.type_name,
                    content="\n".join(structPayload.toProtpBufferContent())
                    ))
        for pa in [item for item in module.pa_apis if item.api in directTransmitList]:
            if pa.mustGenProto():
                structPayload=pa.getPayload().getStructPayload()
                messageList.append(message_template.substitute(
                    name = pa.toProtoBufName(),
                    content="\n".join(structPayload.toProtpBufferContent())
                    ))
    for ecu in ecus:
        for tx in [tx for tx in ecu.txSignals if tx.name in directTransmitList]:
            if not tx.isSingle():
                messageList.append(message_template.substitute(
                    name = tx.name,
                    content="\n".join(tx.toProtoBufContent())
                    ))
    writeFile(outDir, "apvp.proto",lambda file:file.write(SomeIP_proto.substitute(
        messageList="".join(messageList)
    )))
    writeFile(outDir, "Android.bp",lambda file:file.write(Android_bp.substitute(
        name=proto_name
    )))
